package cn.message.web;

import cn.itcast.pojo.horseman;
import cn.itcast.pojo.order;
import cn.itcast.pojo.orderItem;
import cn.itcast.util.OutputStringController;
import cn.message.service.impl.MessageOrderServiceImpl;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.mp.api.WxMpInMemoryConfigStorage;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.api.impl.WxMpServiceImpl;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateData;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateMessage;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Map;

/**
 * @author 辉
 * @title: MessageOrderController
 * @projectName wx_shop
 * @description: TODO
 * @date 2019/6/1821:20
 */
@Slf4j
@RestController
@RequestMapping(value = "/wxshop/message",produces = "text/html;charset=UTF-8")
public class MessageOrderController {
    @Resource
    OutputStringController osc;

    @Resource
    MessageOrderServiceImpl messageOrderService;

    /**
     * 导出订单的excel表格
     * @return
     */
    @ResponseBody
    @RequestMapping("/exportOrderExcel")
    public String exportOrderExcel(@RequestBody Map<String,String> map){
        String results = "";
        List<order> orderList = messageOrderService.exportOrderExcel(map);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        if(orderList.isEmpty()){
            results = osc.resultFailure("订单导出失败","");
        }else {
            for (order order : orderList) {
                if(order.getPayTime() != null){
                    order.setPayTimeString(sdf.format(order.getPayTime()));
                }
            }
            results = osc.resultSuccess("订单导出成功",orderList);
        }
        return results;
    }

    /**
     *功能：获取所有订单信息
     * @author 欧阳辉
     * @date 2019/6/18
     * @param
     * @return java.lang.String
     */
    @PostMapping("/findAllOrder")
    public String findAllOrder(@RequestBody Map<String,String> map){

        String results = "";
        List<order> orders = messageOrderService.findAllProduct(map);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");

        for(int i = 0 ;i<orders.size() ;i++){
            if(StringUtils.isNotBlank(ObjectUtils.toString(orders.get(i).getOrderTime()))){
                orders.get(i).setOrderTimeString(sdf.format(orders.get(i).getOrderTime()));
            }
            if(StringUtils.isNotBlank(ObjectUtils.toString(orders.get(i).getOrderDelivery()))){
                orders.get(i).setOrderDeliveryString(sdf.format(orders.get(i).getOrderDelivery()));
            }
            if(StringUtils.isNotBlank(ObjectUtils.toString(orders.get(i).getUserEvaluateTime()))){
                orders.get(i).setUserEvaluateTimeString(sdf.format(orders.get(i).getUserEvaluateTime()));
            }
            if(StringUtils.isNotBlank(ObjectUtils.toString(orders.get(i).getPayTime()))){
                orders.get(i).setPayTimeString(sdf.format(orders.get(i).getPayTime()));
            }
            if(StringUtils.isNotBlank(ObjectUtils.toString(orders.get(i).getHorsemanArrivalTime()))){
                orders.get(i).setHorsemanArrivalTimeString(sdf.format(orders.get(i).getHorsemanArrivalTime()));
            }
            if(StringUtils.isNotBlank(ObjectUtils.toString(orders.get(i).getHorsemanReceptionTime()))){
                orders.get(i).setHorsemanReceptionTimeString(sdf.format(orders.get(i).getHorsemanReceptionTime()));
            }
            if(StringUtils.isNotBlank(ObjectUtils.toString(orders.get(i).getHorsemanMeasureTime()))){
                orders.get(i).setHorsemanMeasureTimeString(sdf.format(orders.get(i).getHorsemanMeasureTime()));
            }
        }
        if(orders.isEmpty()){
            results = osc.resultFailure("no","");
            log.debug("获取所有产品信息失败");
        }else {
            // 取分页信息
            PageInfo<order> pageInfo = new PageInfo<order>(orders);
            long total = pageInfo.getTotal(); //获取总记录数
            results = osc.resultSuccess("yes",orders,total);
            log.debug("获取所有产品信息成功");
        }

        return results;
    }

    /**
     *功能：获取所有骑手数据
     * @author 欧阳辉
     * @date 2019/6/18
     * @param
     * @return java.lang.String
     */
    @PostMapping("/getAllHorseman")
    public String getAllHorseman(@RequestBody Map<String,String> map){
        log.debug("获取所有骑手数据开始");
        //返回结果
        String results ="";
        //获取页数
        Integer pageNum = Integer.parseInt(map.get("page"));
        //获取每页大小
        Integer pageSize = Integer.parseInt(map.get("limit"));
        //查询类型
        String select = "";
        if(StringUtils.isNotBlank(map.get("select"))){
            select = map.get("select");
        }
        //查询值
        String value = "";
        if(StringUtils.isNotBlank(map.get("value"))){
            value = map.get("value");
        }
        List<horseman> horsemen = messageOrderService.getAllHorseman(pageNum,pageSize,select,value);
        if(horsemen.isEmpty()){
            results = osc.resultFailure("no","");
            log.debug("获取所有骑手数据失败");
        }else {
            // 取分页信息
            PageInfo<horseman> pageInfo = new PageInfo<horseman>(horsemen);
            long total = pageInfo.getTotal(); //获取总记录数
            results = osc.resultSuccess("yes",horsemen,total);
            log.debug("获取所有骑手数据成功");
        }

        return results;
    }


    /**
     *功能：查询订单明细
     * @author 欧阳辉
     * @date 2019/6/18
      * @param map
     * @return java.lang.String
     */
    @PostMapping("/findOrderItem")
    public String findOrderItem(@RequestBody Map<String,String> map){
        log.debug("获取所有产品信息开始");
        //返回结果
        String results ="";
        //获取页数
        Integer orderId = Integer.parseInt(map.get("orderId"));

        List<orderItem> order_items = messageOrderService.findOrderItem(orderId);
        if(order_items==null){
            results = osc.resultFailure("no","");
            log.debug("获取所有产品信息失败");
        }else {
            results = osc.resultSuccess("yes",order_items);
            log.debug("获取所有产品信息成功");
        }

        return results;
    }

    /**
     *
     * @Description:
     * 派单
     * @auther: 欧阳辉
     * @date: 16:49 2020/3/30
     * @param: [map]
     * @return: java.lang.String
     *
     */
    @PostMapping("/sendOrder")
    public String sendOrder(@RequestBody Map<String,String> map){
        log.debug("派单开始");
        //返回结果
        String results ="";
        //获取页数
        Integer orderId = Integer.parseInt(map.get("orderId"));
        String openId = map.get("horesmanOpenId");
        String name = map.get("horesmanName");

        boolean issend = messageOrderService.sendOrder(orderId,openId,name);
        if(!issend){
            results = osc.failure("no");
            log.debug("派单失败");
        }else {
            results = osc.success("yes");
            log.debug("派单成功");
        }

        return results;
    }


    /**
     * 获取access_token
     * @param openId
     * @return
     * @throws Exception
     */
    public void getAccessToken(String openId){
        //1，配置
        WxMpInMemoryConfigStorage wxStorage = new WxMpInMemoryConfigStorage();
        wxStorage.setAppId("wx8153b9b18ebfa8eb");
        wxStorage.setSecret("c8bf9f0c564f7f44a297054995e6eada");
        WxMpService wxMpService = new WxMpServiceImpl();
        wxMpService.setWxMpConfigStorage(wxStorage);

        //2,推送消息
        WxMpTemplateMessage templateMessage = WxMpTemplateMessage.builder()
                .toUser("oFPglwycQbNOq94eE40ZOH-AY98Y")//要推送的用户openid
                .templateId("Xc_tnHReR3n1X91cwATTFitTJwgKDGn2YRhpygiA53U")//模版id
                .url("https://30paotui.com/")//点击模版消息要访问的网址
                .build();
        //3,如果是正式版发送模版消息，这里需要配置你的信息
        templateMessage.addData(new WxMpTemplateData("first", "派单提醒", "#FF00FF"));
        templateMessage.addData(new WxMpTemplateData("keyword1", "有用户下单了，请及时派单", "#FF00FF"));
        templateMessage.addData(new WxMpTemplateData("keyword2", "value", "#FF00FF"));
        templateMessage.addData(new WxMpTemplateData("name", "value", "#FF00FF"));
                        //templateMessage.addData(new WxMpTemplateData("name2", value2, color2));
        try {
            wxMpService.getTemplateMsgService().sendTemplateMsg(templateMessage);
        } catch (Exception e) {
            System.out.println("推送失败：" + e.getMessage());
            e.printStackTrace();
        }

    }

}
